#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpSocket = new QTcpSocket(this),
    last_command = 0,
    cycletmr = new QTimer(this),
    is_tcp_connected = false;
    count_time = 0;
    connect(ui->pb_Connect,SIGNAL(clicked()),   this,SLOT(tcp_connect()));
    connect(ui->pb_Send, SIGNAL(clicked()),     this,SLOT(tcp_send()));
    connect(tcpSocket, SIGNAL(readyRead()),     this,SLOT(tcp_dataready()));
    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(connected()),     this,SLOT(tcp_set_connected()));
    connect(tcpSocket, SIGNAL(disconnected()),  this,SLOT(tcp_set_disconnected()));
    connect(cycletmr, SIGNAL(timeout()),        this,SLOT(tcp_send()));
    connect(ui->ckb_AutoSend,SIGNAL(clicked(bool)),this,SLOT(cycletmrCtrl(bool)));

}

void MainWindow::cycletmrCtrl(bool ctrl){
    if(ctrl){
        qDebug()<<"tcp send is auto runing"<<endl;
        cycletmr->start(ui->spb_AutoSendInternal->value()*1000);
        ui->txtb_Output->append("tcp send auto run");
    }else{
        cycletmr->stop();
    }
}

void MainWindow::timer_run(void){
    QString str="timer outtime";
    qDebug()<<str<<"!"<<endl;
}

void MainWindow::tcp_connect(void){
    if(!is_tcp_connected){
        tcpSocket->abort();
        tcpSocket->connectToHost(ui->le_IP->text(),ui->le_Port->text().toInt());
        qDebug()<<tcpSocket->state()<<endl;
        ui->txtb_Output->append("tcp nonnect ok");
    }
}

void MainWindow::tcp_set_connected(void){
    qDebug()<<"tcp ip connected!"<<endl;
    is_tcp_connected = true;
}

void MainWindow::tcp_set_disconnected(void) {
    qDebug()<<"tcp ip disconnectd"<<endl;
    is_tcp_connected = false;
}

void MainWindow::tcp_send(void){
//    QByteArray test_data;
    QByteArray sdata;
    if(!is_tcp_connected){
           tcpSocket->connectToHost(ui->le_IP->text(), ui->le_Port->text().toInt());
            qDebug()<<"Tcp connected!"<<endl;
    }
    sdata.append((char)0x00);   //command
    sdata.append((char)0x00);   //command index
    sdata.append((char)0x00);   //data length

    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    ui->dte_UpLoad->setDateTime(time);

    QString dt = ui->dte_UpLoad->dateTime().toString("yyyyMMddhhmmss");
    QByteArray dt1 = dt.toLatin1();
    sdata.append(QByteArray::fromHex(dt1)); // date time
    sdata.append(ui->le_devNo->text().toLatin1()); //device number
    sdata.append(ui->le_Gps_signal_qualit->text().toInt());     //gps signal qualit
    sdata.append(ui->le_Gsm_signal_qualit->text().toInt());     //gsm signal qualit
    sdata.append(ui->le_Satellite_cout->text().toInt());        //gsm signal qualit
    float latitude = ui->le_Latitude->text().toFloat();         // Satellite_cout
    char *p = (char *)&latitude;
    sdata.append(*p);sdata.append(*(p+1)); sdata.append(*(p+2)); sdata.append(*(p+3));
    sdata.append('E');
    float longitude = ui->le_Logitue->text().toFloat(); // longitude
    p = (char *)&longitude;
    sdata.append(*p); sdata.append(*(p+1)); sdata.append(*(p+2)); sdata.append(*(p+3));
    sdata.append('N');

    float altitude = ui->le_Altitude->text().toFloat(); // altitude
    p = (char *)&altitude;
    sdata.append(*p); sdata.append(*(p+1)); sdata.append(*(p+2)); sdata.append(*(p+3));

    quint16 engine_speed = ui->le_Engine_speed->text().toUInt();    //engine speed
    p = (char *)&engine_speed;
    sdata.append(*p);sdata.append(*(p+1));

//    p = (char *)&engine_speed;
//    test_data = "";
//    qDebug()<<"test data is null"<< test_data.toHex()<<endl;
//    test_data.append(*p);test_data.append(*(p+1));
//    qDebug()<<"engine_speed test data is"<< test_data.toHex()<<endl;

    sdata.append(ui->le_Water_temp->text().toUInt());       //water temp
    sdata.append(ui->le_Oil_press->text().toUInt());        //oil press

    quint32 worktime = ui->le_Work_time->text().toUInt();    //work time
    p = (char *)&worktime;
    sdata.append(*p);sdata.append(*(p+1));sdata.append(*(p+2)); sdata.append(*(p+3));

//    p = (char *)&worktime;
//    test_data = "";
//    qDebug()<<"test data is null"<< test_data.toHex()<<endl;
//    test_data.append(*p);test_data.append(*(p+1));test_data.append(*(p+2)); test_data.append(*(p+3));
//    qDebug()<<"test data is"<< test_data.toHex()<<endl;



    //number 2 can data
    sdata.append(ui->le_CAN2_1->text().toInt());
    sdata.append(ui->le_CAN2_2->text().toInt());
    sdata.append(ui->le_CAN2_3->text().toInt());
    sdata.append(ui->le_CAN2_4->text().toInt());
    sdata.append(ui->le_CAN2_5->text().toInt());
    sdata.append(ui->le_CAN2_6->text().toInt());
    sdata.append(ui->le_CAN2_7->text().toInt());
    sdata.append(ui->le_CAN2_8->text().toInt());
    //number 3 can data
    sdata.append(ui->le_CAN3_1->text().toInt());
    sdata.append(ui->le_CAN3_2->text().toInt());
    sdata.append(ui->le_CAN3_3->text().toInt());
    sdata.append(ui->le_CAN3_4->text().toInt());
    sdata.append(ui->le_CAN3_5->text().toInt());
    sdata.append(ui->le_CAN3_6->text().toInt());
    sdata.append(ui->le_CAN3_7->text().toInt());
    sdata.append(ui->le_CAN3_8->text().toInt());

    //number 4 can data
    sdata.append(ui->le_CAN4_1->text().toInt());
    sdata.append(ui->le_CAN4_2->text().toInt());
    sdata.append(ui->le_CAN4_3->text().toInt());
    sdata.append(ui->le_CAN4_4->text().toInt());
    sdata.append(ui->le_CAN4_5->text().toInt());
    sdata.append(ui->le_CAN4_6->text().toInt());
    sdata.append(ui->le_CAN4_7->text().toInt());
    sdata.append(ui->le_CAN4_8->text().toInt());
    //number 5 can data
    sdata.append(ui->le_CAN2_1->text().toInt());
    sdata.append(ui->le_CAN2_2->text().toInt());
    sdata.append(ui->le_CAN2_3->text().toInt());
    sdata.append(ui->le_CAN2_4->text().toInt());
    sdata.append(ui->le_CAN2_5->text().toInt());
    sdata.append(ui->le_CAN2_6->text().toInt());
    sdata.append(ui->le_CAN2_7->text().toInt());
    sdata.append(ui->le_CAN2_8->text().toInt());
    //number 5 can data
    sdata.append(ui->le_CAN3_1->text().toInt());
    sdata.append(ui->le_CAN3_2->text().toInt());
    sdata.append(ui->le_CAN3_3->text().toInt());
    sdata.append(ui->le_CAN3_4->text().toInt());
    sdata.append(ui->le_CAN3_5->text().toInt());
    sdata.append(ui->le_CAN3_6->text().toInt());
    sdata.append(ui->le_CAN3_7->text().toInt());
    sdata.append(ui->le_CAN3_8->text().toInt());

    //number 7 can data
    sdata.append(ui->le_CAN4_1->text().toInt());
    sdata.append(ui->le_CAN4_2->text().toInt());
    sdata.append(ui->le_CAN4_3->text().toInt());
    sdata.append(ui->le_CAN4_4->text().toInt());
    sdata.append(ui->le_CAN4_5->text().toInt());
    sdata.append(ui->le_CAN4_6->text().toInt());
    sdata.append(ui->le_CAN4_7->text().toInt());
    sdata.append(ui->le_CAN4_8->text().toInt());
    //number 8 can data
    sdata.append(ui->le_CAN4_1->text().toInt());
    sdata.append(ui->le_CAN4_2->text().toInt());
    sdata.append(ui->le_CAN4_3->text().toInt());
    sdata.append(ui->le_CAN4_4->text().toInt());
    sdata.append(ui->le_CAN4_5->text().toInt());
    sdata.append(ui->le_CAN4_6->text().toInt());
    sdata.append(ui->le_CAN4_7->text().toInt());
    sdata.append(ui->le_CAN4_8->text().toInt());
    //DI DO DOS
    sdata.append(ui->le_DI_byte1->text().toInt());
    sdata.append(ui->le_DI_byte2->text().toInt());
    sdata.append(ui->le_DO_byte1->text().toInt());
    sdata.append(ui->le_DO_byte2->text().toInt());
    sdata.append(ui->le_DOS_byte1->text().toInt());
    sdata.append(ui->le_DOS_byte2->text().toInt());

    QByteArray sdata_packed;
    uint8_t c_sdata_packed[300];
    uint16_t packedlength;
    ui->txtb_Output->append("raw data before send:");
    ui->txtb_Output->append(sdata.toHex());
    int result = exslip_pack((uint8_t *)sdata.data(),sdata.length(),c_sdata_packed,&packedlength);
    sdata_packed.append((const char *)c_sdata_packed, (int)packedlength);


    count_time = count_time+1;;
    qDebug()<<"count_time is "<< count_time<<endl;
    if (count_time == 100){
       ui->txtb_Output->clear();
       count_time = 0;
    }

    ui->txtb_Output->append("packed data before send:");
    ui->txtb_Output->append(sdata_packed.toHex());
    qDebug()<<"Tcp start send!"<<endl;
    tcpSocket->write(sdata_packed);
}

void MainWindow::tcp_dataready(){
    QByteArray b = tcpSocket->read(1024);
    ui->txtb_Output->append("raw data after recv:");
    ui->txtb_Output->append(b.toHex());

    QByteArray rdata_unpacked;
    uint8_t c_rdata_unpacked[300];
    uint16_t unpacked_length;
    QByteArray rdata_command;
    QByteArray display_rdata_command;
    char i;
    char *p;
    int result = exslip_unpack((uint8_t *)b.data(), b.length(), c_rdata_unpacked, &unpacked_length);
    if (result>=0) {
        rdata_unpacked.append((const char *)c_rdata_unpacked, unpacked_length);
        ui->txtb_Output->append("unpacked data after recv:");
        ui->txtb_Output->append(rdata_unpacked.toHex());
    } else {
        ui->txtb_Output->append("unpacked data failed!");
    }
    if (c_rdata_unpacked[0] == 1){
        ui->txtbox_Command_data->append("get a commmand");
        p = (char *)&c_rdata_unpacked[23];
        for(i=0;i<13;i++)
        {
             rdata_command.append(*(p+i));
        }
//         display_rdata_command[0] = rdata_command[0];
//         display_rdata_command[1] = (char)0x00;
//        for(i=1;i<13;i++)
//        {
//            display_rdata_command[i*2] = rdata_command[i];
//            display_rdata_command[2i+1] = (char)0x00;
//        }

        qDebug()<<rdata_command.toHex()<<endl;
        ui->txtbox_Command_data->append(rdata_command.toHex());

    }

}
void MainWindow::displayError(QAbstractSocket::SocketError socketError){
    qDebug()<<"tcp error"<<endl;
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The host was not found. Please check the "
                                    "host name and port settings."));
        break;
    case QAbstractSocket::ConnectionRefusedError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The connection was refused by the peer. "
                                    "Make sure the fortune server is running, "
                                    "and check that the host name and port "
                                    "settings are correct."));
        break;
    default:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The following error occurred: %1.")
                                 .arg(tcpSocket->errorString()));
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
